import 'dart:async';

import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/login/view/login_top_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:roundcheckbox/roundcheckbox.dart';

import '../../network/Api.dart';
import '../../network/http_config.dart';
import '../../utils/loading.dart';
import '../../utils/snack_bar.dart';
import 'WebView.dart';

class registerLoginUI extends StatelessWidget {
  const registerLoginUI({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          Container(
              color: Colors.white,
              child: const SingleChildScrollView(child: _registerLoginPage())),
          Positioned(
            top: ScreenUtil().statusBarHeight + 14,
            left: 0,
            child: GestureDetector(
              onTap: () {
                Get.back();
              },
              child: Container(
                padding: const EdgeInsets.only(left: 10),
                child: Image.asset(
                  'images/map/back_arrow_shop_detail.png',
                  width: 30,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _registerLoginPage extends StatefulWidget {
  const _registerLoginPage({Key? key}) : super(key: key);

  @override
  State createState() {
    return _registerLoginState();
  }
}

class _registerLoginState extends State<_registerLoginPage> {
  var _loginBtnSelector = [0xFFF5F6F6, 0xFF222222];
  final _loginBtnEnable = [0xFFFB6D99, 0xFFFFFFFF];
  final _loginBtnUnable = [0xFFF5F6F6, 0xFF222222];
  final TextEditingController _mobController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  final TextEditingController _passController = TextEditingController();
  final TextEditingController _conPassController = TextEditingController();

  var check = false;
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;
  bool _isObscure1 = true;
  Color _eyeColor1 = Colors.grey;

  @override
  void initState() {
    super.initState();
  }

  getCheckBoxBorderColor() {
    if (check) {
      return const Color(0xFF7F69D9);
    } else {
      return const Color(0xFFD1D1D1);
    }
  }

  Timer? _timer;
  int _curTime = 0;

  _startCountdownTimer() {
    _curTime = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _curTime--;
      });
      if (_curTime <= 0) {
        _timer?.cancel();
      }
    });
  }

  String _smsSig = "";

  //发送验证码
  _sendVerifyCode() {
    print('mmmm');
    if (_mobController.text.length < 11) {
      toast("请输入手机号");
      return false;
    }
    loading(() async {
      final res = await Api.getInstance().loginSendCode(_mobController.text);

      if (res['code'] == 0) {
        if (res['data'] != null && res['data']['sig'] != null) {
          _smsSig = res['data']['sig'];
          _startCountdownTimer();
        }
      }
      toast(res['msg']);
    });
  }

  //注册
  _sendRegister() {
    FocusScope.of(context).unfocus();
    if (!_verify(true)) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance().registerSend(
          _mobController.text,
          _codeController.text,
          _smsSig,
          _passController.text,
          _conPassController.text);
      if (res['code'] == 0 && res['data'] != null) {
        // await Provider.remove("code");
        // await Provider.remove("state");
        // final data = res['data'];
        // Provider.memberId = data['memberId'];
        // // Provider.profilePhoto = data['profilePhoto'];
        // Provider.grma = data['code'];
        // Provider.memberInfo = data;
        // HttpConfig.token = data['token'];
        // Provider.userEaseName = data['emUser']['username'];
        // Provider.userEaseToken = data['userEaseToken'];
        // await Provider.cache("memberId", Provider.memberId);
        // await Provider.cache("qrMa", Provider.grma);
        // await Provider.cache("token", HttpConfig.token);
        // await Provider.cache("username", Provider.userEaseName);
        // await Provider.cache("userEaseToken", Provider.userEaseToken);
        //
        // if (await EMClient.getInstance.isConnected()) {
        // } else {
        //   await EMClient.getInstance
        //       .login(Provider.userEaseName, Provider.userEaseToken, false);
        // }
        // String? inviteCode = await Provider.getCache("inviteCode");
        // if (inviteCode?.isNotEmpty == true) {
        //   await Api.getInstance().invite(Provider.memberId, inviteCode!);
        // }
        //
        // Navigate.toPage(const PersonInformationPage());

        /// 注册完毕，返回登录页面
        Get.back();
        ThemeSnackBar.show(context, res['msg']);
      } else {
        ThemeSnackBar.show(context, res['msg']);
        // toast(res['msg']);
      }
    });
  }

  bool _verify(bool sendCode) {
    if (_mobController.text.length < 11) {
      toast("请输入手机号");
      return false;
    }
    if (_codeController.text.isEmpty) {
      toast("请输入验证码");
      return false;
    }

    if (_passController.text.isEmpty) {
      toast("请输入密码");
      return false;
    }
    if (_conPassController.text.isEmpty) {
      toast("请输入确认密码");
      return false;
    }

    if (check == false) {
      // toast("请仔细阅读并了解《隐私协议》和《服务协议》");
      _versionOfdown(context, "请仔细阅读并了解《隐私协议》和《服务协议》");
      return false;
    }

    return true;
  }

  Future<void> _versionOfdown(context, String title) async {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text.rich(TextSpan(children: [
              const TextSpan(
                  text: "请仔细阅读并同意",
                  style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
              TextSpan(
                text: "《隐私协议》",
                style: TextStyle(color: ThemeColor.appColor, fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return const Browser(
                          '隐私协议', '${HttpConfig.baseUrl}priva');
                    }));
                  },
              ),
              const TextSpan(
                  text: "和",
                  style: TextStyle(color: Color(0xFF222222), fontSize: 12)),
              TextSpan(
                text: "《服务协议》",
                style: TextStyle(color: ThemeColor.appColor, fontSize: 12),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (BuildContext context) {
                      return const Browser('服务协议', '${HttpConfig.baseUrl}serv');
                    }));
                  },
              )
            ])),
            actions: <Widget>[
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: const Text(
                  '不同意',
                  style: TextStyle(fontSize: 16, color: Colors.black),
                ),
              ),
              CupertinoDialogAction(
                onPressed: () {
                  Navigator.pop(context);
                  setState(() {
                    check = true;
                  });
                  _sendRegister();
                },
                child: Text(
                  '同意并继续',
                  style: TextStyle(fontSize: 16, color: ThemeColor.appColor),
                ),
              ),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            const LoginTopView(),
            //手机号
            Container(
              margin: const EdgeInsets.fromLTRB(40, 48, 40, 0),
              height: 45,
              color: const Color(0xFFF6F8FA),
              child: TextField(
                controller: _mobController,
                maxLength: 11,
                keyboardType: TextInputType.phone,
                cursorColor: const Color(0xFFFB6D99),
                style: const TextStyle(fontSize: 12, color: Color(0xFF222222)),
                decoration: InputDecoration(
                  hintText: "请输您的手机号",
                  counterText: "",
                  border: InputBorder.none,
                  hintStyle: const TextStyle(color: Color(0xFF999999)),
                  fillColor: const Color(0xffF1F3FB),
                  filled: true,
                  enabledBorder: const OutlineInputBorder(
                    /*边角*/
                    borderRadius: BorderRadius.all(
                      Radius.circular(5), //边角为30
                    ),
                    borderSide: BorderSide(
                      color: Colors.white54, //边线颜色为黄色
                      width: 1, //边线宽度为2
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Colors.white54, //边框颜色为绿色
                      width: 1, //宽度为5
                    ),
                  ),
                  contentPadding:
                      const EdgeInsets.only(top: 0, bottom: 0, left: 10),
                ),
                onChanged: (e) {
                  setState(() {
                    _loginBtnSelector =
                        _mobController.text.length >= 6 && e.length >= 11
                            ? _loginBtnEnable
                            : _loginBtnUnable;
                  });
                },
              ),
            ),
            //验证码
            Container(
                height: 45,
                margin: const EdgeInsets.fromLTRB(40, 12, 40, 0),
                // padding: const EdgeInsets.symmetric(horizontal: 12),
                // margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
                decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5)),
                    color: const Color(0xFFF3F4F5)),
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _codeController,
                        keyboardType: TextInputType.phone,
                        maxLength: 11,
                        maxLines: 1,
                        style: TextStyle(
                          fontSize: 12,
                          color: ThemeColor.textColor,
                        ),
                        decoration: const InputDecoration(
                          hintText: "请输入验证码",
                          border: InputBorder.none,
                          counterText: '',
                          hintStyle: TextStyle(color: Color(0xFF999999)),
                          fillColor: Color(0xffF1F3FB),
                          filled: true,
                        ),
                      ),
                    ),
                    Container(
                        width: 102,
                        height: 30,
                        decoration: BoxDecoration(
                          // border: Border.all(color: const Color(0xFF2C7FF8)),
                          borderRadius: BorderRadius.circular(15),
                          color: ThemeColor.colorCF8F23,
                        ),
                        alignment: Alignment.center,
                        child: GestureDetector(
                          onTap: () {
                            _sendVerifyCode();
                          },
                          child: Text(
                            _curTime > 0 ? "$_curTime秒后重新获取" : "获取验证码",
                            style: const TextStyle(
                                color: Colors.white, fontSize: 12),
                          ),
                        ))
                  ],
                )),
            //密码
            Container(
              margin: const EdgeInsets.fromLTRB(40, 12, 40, 0),
              height: 42,
              child: TextField(
                controller: _passController,
                maxLength: 16,
                obscureText: _isObscure,
                keyboardType: TextInputType.text,
                cursorColor: ThemeColor.mainColor,
                style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
                decoration: InputDecoration(
                  hintText: "请输入6-18位新密码（数字/字母/字符)",
                  counterText: "",
                  border: InputBorder.none,
                  hintStyle: const TextStyle(color: Color(0xFF999999)),
                  fillColor: const Color(0xffF1F3FB),
                  filled: true,
                  enabledBorder: const OutlineInputBorder(
                    /*边角*/
                    borderRadius: BorderRadius.all(
                      Radius.circular(5), //边角为30
                    ),
                    borderSide: BorderSide(
                      color: Colors.white54, //边线颜色为黄色
                      width: 1, //边线宽度为2
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Colors.white54, //边框颜色为绿色
                      width: 1, //宽度为5
                    ),
                  ),
                  contentPadding:
                      const EdgeInsets.only(top: 0, bottom: 0, left: 10),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _isObscure ? Icons.visibility_off : Icons.visibility,
                      color: _eyeColor,
                      size: 16,
                    ),
                    onPressed: () {
                      setState(() {
                        if (_isObscure) {
                          _isObscure = !_isObscure;
                        } else {
                          _isObscure = true;
                        }

                        _eyeColor = (_isObscure
                            ? Colors.grey
                            : Theme.of(context).iconTheme.color)!;
                      });
                    },
                  ),
                ),
                onChanged: (e) {
                  setState(() {
                    _loginBtnSelector =
                        _mobController.text.length >= 11 && e.length >= 6
                            ? _loginBtnEnable
                            : _loginBtnUnable;
                  });
                },
              ),
            ),
            //新密码
            Container(
              margin: const EdgeInsets.fromLTRB(40, 12, 40, 0),
              height: 42,
              child: TextField(
                controller: _conPassController,
                maxLength: 16,
                obscureText: _isObscure1,
                keyboardType: TextInputType.text,
                cursorColor: ThemeColor.mainColor,
                style: TextStyle(fontSize: 12, color: ThemeColor.textColor),
                decoration: InputDecoration(
                  hintText: "确认新密码",
                  counterText: "",
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                  fillColor: const Color(0xffF1F3FB),
                  filled: true,
                  enabledBorder: const OutlineInputBorder(
                    /*边角*/
                    borderRadius: BorderRadius.all(
                      Radius.circular(5), //边角为30
                    ),
                    borderSide: BorderSide(
                      color: Colors.white54, //边线颜色为黄色
                      width: 1, //边线宽度为2
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(
                      color: Colors.white54, //边框颜色为绿色
                      width: 1, //宽度为5
                    ),
                  ),
                  contentPadding:
                      const EdgeInsets.only(top: 0, bottom: 0, left: 10),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _isObscure1 ? Icons.visibility_off : Icons.visibility,
                      color: _eyeColor1,
                      size: 16,
                    ),
                    onPressed: () {
                      setState(() {
                        _isObscure1 = !_isObscure1;

                        _eyeColor1 = (_isObscure1
                            ? Colors.grey
                            : Theme.of(context).iconTheme.color)!;
                      });
                    },
                  ),
                ),
              ),
            ),
            //确认
            GestureDetector(
              child: Container(
                  margin: const EdgeInsets.fromLTRB(40, 30, 40, 0),
                  height: 45,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(22.5)),
                    color: ThemeColor.colorCF8F23,
                  ),
                  width: double.maxFinite,
                  child: const Center(
                    child: Text(
                      "注册",
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                  )),
              onTap: () {
                _sendRegister();
              },
            ),
            GestureDetector(
              onTap: () {
                if (check) {
                  check = false;
                } else {
                  check = true;
                }
                setState(() {});
              },
              child: Container(
                color: Colors.white,
                padding: const EdgeInsets.only(top: 14),
                margin: const EdgeInsets.symmetric(horizontal: 40),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    RoundCheckBox(
                        size: 16,
                        //checkBox大小
                        checkedWidget: const Icon(
                          Icons.check,
                          color: Colors.white,
                          size: 8,
                        ),
                        checkedColor: ThemeColor.colorCF8F23,
                        uncheckedColor: Colors.white,
                        border:
                            Border.all(color: ThemeColor.colorCF8F23, width: 1),
                        isChecked: check,
                        onTap: (selected) {
                          if (check) {
                            check = false;
                          } else {
                            check = true;
                          }
                          setState(() {});
                        }),
                    Center(
                        child: Text.rich(TextSpan(children: [
                      const TextSpan(
                        text: " 我已阅读并同意",
                        style:
                            TextStyle(color: Color(0xFF3A3A3A), fontSize: 10),
                      ),
                      TextSpan(
                        text: "《隐私协议》",
                        style: TextStyle(
                            color: ThemeColor.colorCF8F23, fontSize: 10),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push(context, MaterialPageRoute(
                                builder: (BuildContext context) {
                              return const Browser(
                                  '隐私协议', '${HttpConfig.baseUrl}priva');
                            }));
                          },
                      ),
                      TextSpan(
                        text: "《服务协议》",
                        style: TextStyle(
                            color: ThemeColor.colorCF8F23, fontSize: 10),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Navigator.push(context, MaterialPageRoute(
                                builder: (BuildContext context) {
                              return const Browser(
                                  '服务协议', '${HttpConfig.baseUrl}serv');
                            }));
                            // setState(() {
                            //   if(check){
                            //     check =false;
                            //   }else{
                            //     check=true;
                            //   }
                            // });
                          },
                      )
                    ]))),
                  ],
                ),
              ),
            ),
            SizedBox(height: 44.w),
          ],
        ),
      ],
    );
  }
}
